package cn.stylefeng.guns.modular.basic.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.CangGuanRoleId;
import cn.stylefeng.guns.modular.basic.entity.BasicDriver;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.mapper.BasicDriverMapper;
import cn.stylefeng.guns.modular.basic.model.params.BasicDriverParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicDriverResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import  cn.stylefeng.guns.modular.basic.service.BasicDriverService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.order.model.params.DealWithParam;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 驾驶员信息表 服务实现类
 */
@Service
public class BasicDriverServiceImpl extends ServiceImpl<BasicDriverMapper, BasicDriver> implements BasicDriverService {

    @Override
    public void add(BasicDriverParam param){
        BasicDriver entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BasicDriverParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BasicDriverParam param){
        BasicDriver oldEntity = getOldEntity(param);
        BasicDriver newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BasicDriverResult findBySpec(BasicDriverParam param, Long operateId){
        return this.baseMapper.findBySpec(param, operateId);
    }

    @Override
    public List<BasicDriverResult> findListBySpec(BasicDriverParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BasicDriverParam param,String condition, Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param, condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(BasicDriverParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BasicDriver getOldEntity(BasicDriverParam param) {
        return this.getById(getKey(param));
    }

    private BasicDriver getEntity(BasicDriverParam param) {
        BasicDriver entity = new BasicDriver();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    
	private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }

    }
    
    @Resource
    BasicOperateService basicOperateService;

    @Resource
    private UserService userService;

	@Transactional(rollbackFor = Exception.class,timeout=300)
	public ResponseData getExceldata2(MultipartFile file, UserDto user, ResponseData data) throws IOException{
		User meuser = userService.getcurrentUser();
		if (ToolUtil.isEmpty(user.getDeptId())) {
			data.setSuccess(false);
			data.setMessage("Please select a Department");
			return data;
		}
		if (ToolUtil.isEmpty(user.getRoleId())) {
			data.setSuccess(false);
			data.setMessage("Please select a Role");
			return data;
		}
		
    	DealWithParam dealWithParam = new DealWithParam();
    	dealWithParam.setNewCustomersflag(false);
		
		String fileName = file.getOriginalFilename();
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Incorrect Upload File Format");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

	        //添加账号
	        UserDto userDto = new UserDto();
	        userDto.setRoleId(user.getRoleId());
	        userDto.setDeptId(user.getDeptId());
	        userDto.setStatus("ENABLE");
	        userDto.setDeliverId(meuser.getDeliverId());
	        userDto.setDeliverName(meuser.getDeliverName());
	        userDto.setOperateId(meuser.getOperateId());
	        
            String  account = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(account)) {
            	userDto.setAccount(account);

		    	User usersf = userService.getByAccount(account);
		    	if(usersf != null) {
					dealWithParam.setNewCustomersflag(true);
					dealWithParam.setNewCustomers(dealWithParam.getNewCustomers()+"Account："+account+"Already Exists；");
					continue;
		    	}
			} 

            String  name = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(name)) {
            	userDto.setName(name);
			} 

            String  password = getCellValue(row.getCell(2));
            if (ToolUtil.isNotEmpty(password)) {
            	userDto.setPassword(password);
			} 

            String  sex = getCellValue(row.getCell(3));
            if (ToolUtil.isNotEmpty(sex)) {
            	if(sex.equals("男")) {
                	userDto.setSex("M");
            	} else {
                	userDto.setSex("F");
            	}
			} 

            String  phone = getCellValue(row.getCell(4));
            if (ToolUtil.isNotEmpty(phone)) {
            	userDto.setPhone(phone);
			} 

            String  getUnit = getCellValue(row.getCell(5));
            if (ToolUtil.isNotEmpty(getUnit)) {
            	userDto.setGetUnit(getUnit);
            	
            	BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
            	basicPutgoodsParam.setDeptId(user.getDeptId());
            	basicPutgoodsParam.setPutgoodsName(getUnit);
            	BasicPutgoodsResult basicPutgoodsResult = basicPutgoodsService.findBySpec(basicPutgoodsParam, null);
            	if(basicPutgoodsResult != null) {
            		userDto.setGetUnitId(Long.parseLong(basicPutgoodsResult.getId()+""));
            	} 
			} 
	        userService.addUser(userDto);
        }
		data.setSuccess(true);
		if (dealWithParam.isNewCustomersflag()) {
			data.setMessage(dealWithParam.getNewCustomers().replaceAll("null", ""));
		}
		return data;
	}

    @Resource
    private BasicPutgoodsService basicPutgoodsService;

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData getExceldata(MultipartFile file, BasicDriverParam basicDriverParam, ResponseData data) throws IOException {
		if (ToolUtil.isEmpty(basicDriverParam.getDriverOperateId())) {
			data.setSuccess(false);
			data.setMessage("Please select a Branch Company");
			return data;
		}
		User meuser = userService.getcurrentUser();
		
		String fileName = file.getOriginalFilename();
		List<BasicDriverParam> list = new ArrayList<BasicDriverParam>();
		BasicOperate basicOperate = basicOperateService.getById(basicDriverParam.getDriverOperateId());
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Incorrect Upload File Format");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            BasicDriverParam bd = new BasicDriverParam();
            bd.setDeliverId(meuser.getDeliverId());
            bd.setDeptId(meuser.getDeptId());
            bd.setDriverOperateId(basicDriverParam.getDriverOperateId());
            bd.setDriverOperateName(basicOperate.getOperateName());
            bd.setCreateTime(new Date());
            
            String  driverName = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(driverName)) {
				bd.setDriverName(driverName);
			} else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
	    		return ResponseData.error("Driver Name cannot be empty");
			}

            String  idcard = getCellValue(row.getCell(2));
            if (ToolUtil.isNotEmpty(idcard)) {
				bd.setIdcard(idcard);
			} 

            String  tel = getCellValue(row.getCell(3));
            if (ToolUtil.isNotEmpty(tel)) {
				bd.setTel(tel);
			} 

            String  driverNumber = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(driverNumber)) {
            	bd.setDriverNumber(driverNumber);
		    	User user = userService.getByAccount(bd.getDriverNumber());
		    	if(user != null) {
	                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
		    		return ResponseData.error(driverNumber+"Already Registered");
		    	}
		        //添加账号
		        UserDto userDto = new UserDto();
		        userDto.setAccount(bd.getDriverNumber());
		        userDto.setPassword("111111");
		        userDto.setName(bd.getDriverName());
		        userDto.setSex("M");
		        userDto.setPhone(bd.getTel());
		        userDto.setRoleId(CangGuanRoleId.SJRoleId.toString());
		        userDto.setDeptId(meuser.getDeptId());
		        userDto.setStatus("ENABLE");
		        userDto.setDeliverId(meuser.getDeliverId());
		        userDto.setDeliverName(meuser.getDeliverName());
		        userDto.setOperateId(meuser.getOperateId());
		        userService.addUser(userDto);
		        user = userService.getByAccount(bd.getDriverNumber());
		        bd.setUserId(user.getUserId());
			} else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
	    		return ResponseData.error("Jilu Account cannot be empty");
			}

            String  six = getCellValue(row.getCell(4));
            if (ToolUtil.isNotEmpty(six)) {
				bd.setSix(six);
			} 

            String  age = getCellValue(row.getCell(5));
            if (ToolUtil.isNotEmpty(age)) {
				bd.setAge(age);
			} 

            String  payee = getCellValue(row.getCell(6));
            if (ToolUtil.isNotEmpty(payee)) {
				bd.setPayee(payee);
			} 

            String  bank = getCellValue(row.getCell(7));
            if (ToolUtil.isNotEmpty(bank)) {
				bd.setBank(bank);
			} 

            String  bankAddress = getCellValue(row.getCell(8));
            if (ToolUtil.isNotEmpty(bankAddress)) {
				bd.setBankAddress(bankAddress);
			} 

            String  bankAccount = getCellValue(row.getCell(9));
            if (ToolUtil.isNotEmpty(bankAccount)) {
				bd.setBankAccount(bankAccount);
			} 

            String  bankNo = getCellValue(row.getCell(10));
            if (ToolUtil.isNotEmpty(bankNo)) {
				bd.setBankNo(bankNo);
			} 

            String  cycle = getCellValue(row.getCell(11));
            if (ToolUtil.isNotEmpty(cycle)) {
				bd.setCycle(cycle);
			} 

            String  taxRate = getCellValue(row.getCell(12));
            if (ToolUtil.isNotEmpty(taxRate)) {
				bd.setTaxRate(taxRate);
			} 

            String  oilCardNumber = getCellValue(row.getCell(13));
            if (ToolUtil.isNotEmpty(oilCardNumber)) {
				bd.setOilCardNumber(oilCardNumber);
			} 
            
            list.add(bd);
        }
        if (list.size() > 0) {
        	saveBatchList(list);
		}
		
        data.setSuccess(true);
		return data;
	}

	@Override
	public boolean saveBatchList(List<BasicDriverParam> list) {
		return this.baseMapper.saveBatchList(list);
	}

	@Override
	public Integer addReturnId(BasicDriverParam basicDriverParam) {
		return this.baseMapper.addReturnId(basicDriverParam);
	}


    @Override
    public BasicDriverResult synchronization(BasicDriverParam basicDriverParam) {
        return this.baseMapper.synchronization(basicDriverParam);
    }

    @Override
    public BasicDriverResult findByName(String name, Long operateId) {
        return null;
    }

}
